home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / pyshared / LanguageSelector / LanguageSelector.py < prev    next >
Encoding:
Python Source  |  2009-05-07  |  8.3 KB  |  217 lines

  1. # (c) 2006 Canonical
  2. # Author: Michael Vogt <michael.vogt@ubuntu.com>
  3. #
  4. # Released under the GPL
  5. #
  6.  
  7. import warnings
  8. warnings.filterwarnings("ignore", "apt API not stable yet", FutureWarning)
  9. import apt
  10. import apt_pkg
  11. import os.path
  12. import shutil
  13. import subprocess
  14. import thread
  15. import time
  16. import gettext
  17. import sys
  18. import string
  19. import tempfile
  20. import re
  21.  
  22. import FontConfig
  23. from gettext import gettext as _
  24. from LocaleInfo import LocaleInfo
  25.  
  26. from LangCache import *                
  27.  
  28.  
  29. # the language-selector abstraction
  30. class LanguageSelectorBase(object):
  31.     """ base class for language-selector code """
  32.     def __init__(self, datadir=""):
  33.         self._datadir = datadir
  34.         # load the localeinfo "database"
  35.         self._localeinfo = LocaleInfo("%s/data/languagelist" % self._datadir)
  36.         self._cache = None
  37.  
  38.     def openCache(self, progress):
  39.         self._cache = LanguageSelectorPkgCache(self._localeinfo, progress)
  40.  
  41.     def getMissingLangPacks(self):
  42.         """
  43.         return a list of langauge packs that are not installed
  44.         but should be installed
  45.         """
  46.         missing = []
  47.         for langInfo in  self._cache.getLanguageInformation():
  48.             #print langInfo.languageCode
  49.             trans_package = "language-pack-%s" % langInfo.languageCode
  50.             # we have a langpack installed, see if we have all of them
  51.             if (self._cache.has_key(trans_package) and 
  52.                 self._cache[trans_package].isInstalled):
  53.                 #print "IsInstalled: %s " % trans_package
  54.                 for (pkg, translation) in self._cache.pkg_translations:
  55.                     missing += self.missingTranslationPkgs(pkg, translation+langInfo.languageCode)
  56.  
  57.         # now check for a missing default language support
  58.         default_lang = self.getSystemDefaultLanguage()
  59.         # if there is no default lang, return early
  60.         if default_lang is None:
  61.             return missing
  62.         if "_" in default_lang:
  63.             default_lang = default_lang.split("_")[0]
  64.         trans_package = "language-pack-%s" % default_lang
  65.         if (self._cache.has_key(trans_package) and 
  66.             not self._cache[trans_package].isInstalled):
  67.             missing += [trans_package]
  68.             for (pkg, translation) in self._cache.pkg_translations:
  69.                 missing += self.missingTranslationPkgs(pkg, translation+default_lang)
  70.         support_packages = LanguageSelectorPkgCache._getPkgList(self._cache, default_lang)
  71.         for support_package in support_packages:
  72.             if (self._cache.has_key(support_package) and 
  73.                 not self._cache[support_package].isInstalled):
  74.                 missing.append(support_package)
  75.  
  76.         return missing
  77.  
  78.     def getUserDefaultLanguage(self):
  79.         fname = os.path.expanduser("~/.dmrc")
  80.         if os.path.exists(fname):
  81.             for line in open(fname):
  82.                 match = re.match(r'Language=(.*)$',line)
  83.                 if match:
  84.                     if "." in match.group(1):
  85.                         return match.group(1).split(".")[0]
  86.                     else:
  87.                         return match.group(1)
  88.         return None
  89.  
  90.     def getSystemDefaultLanguage(self):
  91.         conffiles = ["/etc/default/locale", "/etc/environment"]
  92.         for fname in conffiles:
  93.             if os.path.exists(fname):
  94.                 for line in open(fname):
  95.                     match = re.match(r'LANG="(.*)"$',line)
  96.                     if match:
  97.                         if "." in match.group(1):
  98.                             return match.group(1).split(".")[0]
  99.                         else:
  100.                             return match.group(1)
  101.         return None
  102.  
  103.     def runAsRoot(self, cmd):
  104.         " abstract interface for the frontends to run specific commands as root"
  105.         # compatibilty code for frontends that already run as root
  106.         if os.getuid() == 0:
  107.             return subprocess.call(cmd)
  108.         # 
  109.         raise AttributeError, "this method needs to be overwriten by the subclass"
  110.  
  111.     def setSystemDefaultLanguage(self, defaultLanguageCode):
  112.         " this updates the system default language "
  113.         conffiles = ["/etc/default/locale", "/etc/environment"]
  114.         for fname in conffiles:
  115.             out = tempfile.NamedTemporaryFile()        
  116.             foundLanguage = False  # the LANGUAGE var
  117.             foundLang = False      # the LANG var
  118.             if os.path.exists(fname):
  119.                 # look for the line
  120.                 for line in open(fname):
  121.                     tmp = string.strip(line)
  122.                     if tmp.startswith("LANGUAGE="):
  123.                         foundLanguage = True
  124.                         line="LANGUAGE=\"%s\"\n" % self._localeinfo.makeEnvString(defaultLanguageCode)
  125.                         #print line
  126.                     if tmp.startswith("LANG="):
  127.                         foundLang = True
  128.                         # we always write utf8 languages
  129.                         line="LANG=\"%s.UTF-8\"\n" % defaultLanguageCode
  130.                     out.write(line)
  131.                     #print line
  132.             # if we have not found them add them
  133.             if foundLanguage == False:
  134.                 line="LANGUAGE=\"%s\"\n" % self._localeinfo.makeEnvString(defaultLanguageCode)
  135.                 out.write(line)
  136.             if foundLang == False:
  137.                 line="LANG=\"%s.UTF-8\"\n" % defaultLanguageCode
  138.                 out.write(line)
  139.             out.flush()
  140.             self.runAsRoot(["/bin/cp",out.name, fname])
  141.  
  142.         # now set the fontconfig-voodoo
  143.         fc = FontConfig.FontConfigHack()
  144.         #print defaultLanguageCode
  145.         #print fc.getAvailableConfigs()
  146.         if defaultLanguageCode in fc.getAvailableConfigs():
  147.             self.runAsRoot(["fontconfig-voodoo", "-f",
  148.                             "--set=%s" % defaultLanguageCode])
  149.         else:
  150.             self.runAsRoot(["fontconfig-voodoo","-f","--remove-current"])
  151.  
  152.     def setUserDefaultLanguage(self, defaultLanguageCode):
  153.         " this updates the user default language "
  154.         fname = os.path.expanduser("~/.dmrc")
  155.         out = tempfile.NamedTemporaryFile()        
  156.         foundLang = False      # the Language var
  157.         if os.path.exists(fname):
  158.             # look for the line
  159.             for line in open(fname):
  160.                 tmp = string.strip(line)
  161.                 if tmp.startswith("Language="):
  162.                     foundLang = True
  163.                     # we always write utf8 languages
  164.                     line="Language=%s.UTF-8\n" % defaultLanguageCode
  165.                 out.write(line)
  166.         # if we have not found them add them
  167.         if foundLang == False:
  168.             line="Language=%s.UTF-8\n" % defaultLanguageCode
  169.             out.write(line)
  170.         out.flush()
  171.         shutil.copy(out.name, fname)
  172.         os.chmod(fname, 0644)
  173.  
  174.         # FIXME: This should be set on a per user base in ~/.fonts.conf
  175.         ## now set the fontconfig-voodoo
  176.         #fc = FontConfig.FontConfigHack()
  177.         ##print defaultLanguageCode
  178.         ##print fc.getAvailableConfigs()
  179.         #f defaultLanguageCode in fc.getAvailableConfigs():
  180.         #    self.runAsRoot(["fontconfig-voodoo", "-f",
  181.         #                    "--set=%s" % defaultLanguageCode])
  182.         #else:
  183.         #    self.runAsRoot(["fontconfig-voodoo","-f","--remove-current"])
  184.  
  185.     def missingTranslationPkgs(self, pkg, translation_pkg):
  186.         """ this will check if the given pkg is installed and if
  187.             the needed translation package is installed as well
  188.  
  189.             It returns a list of packages that need to be 
  190.             installed
  191.         """
  192.  
  193.         # FIXME: this function is called too often and it's too slow
  194.         # -> see ../TODO for ideas how to fix it
  195.         missing = []
  196.         # check if the pkg itself is available and installed
  197.         if not self._cache.has_key(pkg):
  198.             return missing
  199.         if not self._cache[pkg].isInstalled:
  200.             return missing
  201.  
  202.         # match every packages that looks similar to translation_pkg
  203.         # 
  204.         for pkg in self._cache:
  205.             if (pkg.name == translation_pkg or
  206.                 pkg.name.startswith(translation_pkg+"-")):
  207.                 if not pkg.isInstalled and pkg.candidateVersion != None:
  208.                     missing.append(pkg.name)
  209.         return missing
  210.         
  211.  
  212. if __name__ == "__main__":
  213.     lsb = LanguageSelectorBase(datadir="..")
  214.     lsb.openCache(apt.progress.OpProgress())
  215.     print lsb.verifyPackageLists()
  216.  
  217.